package com.zb.task;

import com.alibaba.fastjson.JSON;
import com.zb.entity.TbTaskModel;
import com.zb.service.TbTaskService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Component
public class MyTask {

    @Autowired
    private TbTaskService tbTaskService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Scheduled(cron = "0/30 * * * * ?")
    public void job() {
        System.out.println("定时任务");
        List<TbTaskModel> tbTaskModels = tbTaskService.beforeOneMinuteOrder();
        for (TbTaskModel taskModel : tbTaskModels) {
            System.out.println(taskModel);
            this.send(taskModel);
        }
    }

    @Transactional
    public void send(TbTaskModel taskModel) {
        //获取最新数据
        taskModel = tbTaskService.getById(taskModel.getId());
        //验证
        if (taskModel != null) {
            if (tbTaskService.lock(taskModel.getId(), taskModel.getVersion()) > 0) {
                rabbitTemplate.convertAndSend(taskModel.getMqExchange(), taskModel.getMqRoutingkey(), JSON.toJSONString(taskModel));
                taskModel.setUpdateTime(new Date());
                taskModel.setVersion(taskModel.getVersion() + 1);
                tbTaskService.updateById(taskModel);
            }
        }
    }
}
